package com.icetech.eom.controller.tx;


import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.icetech.commonbase.ResultTools;
import com.icetech.commonbase.constants.CodeConstantsEnum;
import com.icetech.commonbase.domain.Page;
import com.icetech.commonbase.domain.response.ObjectResponse;
import com.icetech.commonbase.domain.response.R;
import com.icetech.eom.common.annotation.SystemLog;
import com.icetech.eom.controller.BaseController;
import com.icetech.eom.controller.vo.DeviceVo;
import com.icetech.eom.dao.tx.UDevDao;
import com.icetech.eom.domain.sys.Custom;
import com.icetech.eom.domain.sys.User;
import com.icetech.eom.domain.tx.Device;
import com.icetech.eom.domain.tx.UDev;
import com.icetech.eom.domain.tx.dto.DeviceDto;
import com.icetech.eom.domain.tx.dto.UserDeviceDto;
import com.icetech.eom.service.sys.ICustomService;
import com.icetech.eom.service.tx.IDeviceService;
import com.icetech.eom.service.tx.IUDevService;
import com.icetech.eom.service.utils.SecurityUtil;
import com.sargeraswang.util.ExcelUtil.ExcelLogs;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  设备管理controller
 * </p>
 *
 * @author wangzw
 * @since 2018-11-12
 */
@Api(value = "Server-API",description = "这是设备接口详细信息的描述")
@RestController
@RequestMapping("/device")
public class DeviceController extends BaseController {

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IUDevService iuDevService;
    @Autowired
    private  SecurityUtil securityUtil;
    @Autowired
    private UDevDao uDevDao;
    @Autowired
    private ICustomService customService;
    private static Md5PasswordEncoder md5encoder = new Md5PasswordEncoder();

    /**
     * 获取设备列表
     */
    @ApiOperation(value = "获取设备列表", notes = "根据查询信息获取设备列表，返回List<Device>类型用户信息的JSON")
    @SystemLog(description = "获取设备列表")
    @RequestMapping(value = "/listpage",method = RequestMethod.GET)
    public ObjectResponse<Page> getDevices(@RequestParam(value = "searchKey",defaultValue = "")String searchKey,
                                           @RequestParam(value = "page",defaultValue = "1")Integer page,
                                           @RequestParam(value = "pageSize",defaultValue = "20")Integer pageSize){
        User currUser = securityUtil.getCurrUser();
        //获取设备列表信息
        PageInfo<DeviceDto> pageInfo = deviceService.selectByPage(searchKey, page, pageSize,currUser.getOrgId());
        return ResultTools.getPageResponse(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPages());
    }


    @ApiOperation(value = "获取当前用户未绑定的设备信息", notes = "根据查询信息获取设备列表，返回List<Device>类型用户信息的JSON")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @SystemLog(description = "获取当前用户未绑定的设备信息")
    public ObjectResponse getList( @RequestParam(value = "page",defaultValue = "1")Integer page,
                                   @RequestParam(value = "pageSize",defaultValue = "20") Integer pageSize,
                                   @RequestParam("userId") Long userId,
                                   @RequestParam("uid") String uid,
                                   @RequestParam("fromUid")String fromUid,
                                   @RequestParam("toUid")String toUid){
        //获取未绑定设备列表信息
        User currUser = securityUtil.getCurrUser();
        PageInfo<DeviceDto> pageInfo = deviceService.selectListUnBindDevice(page, pageSize, userId, uid, fromUid, toUid, currUser.getOrgId());
        return ResultTools.getPageResponse(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPages());
    }
    /**
     * 增加设备
     */
    @ApiOperation(value = "设备添加", notes = "添加设备信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @SystemLog(description = "设备添加")
    public ObjectResponse add(@RequestBody DeviceVo deviceVo){
        User user = securityUtil.getCurrUser();
        Device device = new Device();
        BeanUtils.copyProperties(deviceVo, device);
        device.setCreator(user.getUserName());
        //设置密码
        device.setPasswd(md5encoder.encodePassword(device.getGuid(),"").substring(0,10));
        boolean isSuccess = deviceService.save(device);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 编辑设备
     */
    @SystemLog(description = "设备编辑")
    @ApiOperation(value = "设备编辑", notes = "编辑设备信息")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ObjectResponse edit(@RequestBody DeviceVo deviceVo){
        User user = securityUtil.getCurrUser();
        Device device = new Device();
        BeanUtils.copyProperties(deviceVo, device);
        device.setModifier(user.getUserName());
        boolean isSuccess = deviceService.updateById(device);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 删除设备
     */
    @ApiOperation(value = "设备删除", notes = "删除设备信息")
    @SystemLog(description = "设备删除")
    @RequestMapping(value = "/remove",method = RequestMethod.GET)
    public ObjectResponse remove(@RequestParam("id")Long id){
        Device device = deviceService.getById(id);
        if (Objects.isNull(device)){
            return ResultTools.fail(CodeConstantsEnum.ERROR_404.getCode(),CodeConstantsEnum.ERROR_404.getDesc());
        }
        boolean isSuccess = deviceService.removeById(id);
        //删除绑定信息
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("dev_id",id);
        uDevDao.deleteByMap(params);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }
    /**
     * 删除设备
     */
    @ApiOperation(value = "设备批量删除", notes = "批量删除设备信息")
    @SystemLog(description = "设备批量删除")
    @RequestMapping(value = "/batchremove",method = RequestMethod.GET)
    public ObjectResponse batchRemove(@RequestParam("ids") List<Long> ids){
        boolean isSuccess = deviceService.removeByIds(ids);
        //删除设备用户绑定关系
        ids.forEach(integer -> {
            HashMap<String, Object> params = Maps.newHashMap();
            params.put("dev_id",integer);
            uDevDao.deleteByMap(params);
        });
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 导出操作
     */
    @ApiOperation(value = "设备批量导出", notes = "批量导出设备信息")
    @SystemLog(description = "设备批量导出")
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public ObjectResponse export(@RequestParam(value = "searchKey",defaultValue = "") String searchKey, HttpServletResponse response){
        try {
            User currUser = securityUtil.getCurrUser();
            Workbook workbook = deviceService.exportExcel(searchKey,currUser.getOrgId());
            String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".xls";
            setFileResponse(response, fileName);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
        }
        return ResultTools.success(null);
    }

    @ApiOperation(value = "设备批量导入", notes = "批量导出设备信息")
    @SystemLog(description = "设备批量导入")
    @RequestMapping(value = "import",method = RequestMethod.POST)
    public R importExcel(@RequestParam(value="file",required=false) MultipartFile file) throws IOException {
        User userEntity = securityUtil.getCurrUser();
        Collection<Map> deviceImportDtos = ExcelUtil.importExcel(Map.class,file.getInputStream(),"yyyy/MM/dd HH:mm:ss",new ExcelLogs(),0);
        deviceImportDtos.forEach(obj->{
            String guid = (String) obj.get("设备UID");
            String cusCode =(String) obj.get("客户编号");
            String devName =(String) obj.get("相机名称");
            //查看设备是否存在
            Custom custom = customService.selectByCode(cusCode);
            Device device = new Device();
            device.setDevName(devName);
            if (Objects.nonNull(custom)){
                //设置所属客户
                device.setOrgId(Long.valueOf(custom.getId()));
            }
            device.setGuid(guid.trim());
            device.setPasswd(md5encoder.encodePassword(guid.trim(),"").substring(0,10));
            Device old = deviceService.findByUid(device.getGuid());
            if (Objects.isNull(old)){
                device.setDevType(Boolean.FALSE);
                device.setIsEnabled(Boolean.TRUE);
                device.setCreator(userEntity.getUserName());
                deviceService.save(device);
            }
        });
        return R.ok();
    }

    /**
     * 获取绑定用户列表信息
     */
    @ApiOperation(value = "获取绑定用户信息", notes = "获取绑定用户信息")
    @SystemLog(description = "获取绑定用户信息")
    @RequestMapping(value = "/listuser",method = RequestMethod.GET)
    public ObjectResponse getBindUsers(@RequestParam(value = "deviceId",defaultValue = "") Long deviceId){
        List<UserDeviceDto> userDeviceDtos = iuDevService.selectBindUsers(deviceId);
        return ResultTools.success(userDeviceDtos);
    }

    /**
     * 解除绑定用户
     */
    @ApiOperation(value = "解除绑定用户", notes = "解除绑定用户")
    @SystemLog(description = "解除绑定用户")
    @RequestMapping(value = "/unbind",method = RequestMethod.GET)
    public ObjectResponse cancelBind(@RequestParam(value = "deviceId",defaultValue = "") Long deviceId,@RequestParam(value = "userId",defaultValue = "") Long userId){
        boolean isSuccess = iuDevService.cancelBind(deviceId,userId);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 批量解除绑定用户
     */
    @ApiOperation(value = "批量解除绑定用户", notes = "解除绑定用户")
    @SystemLog(description = "批量解除绑定用户")
    @RequestMapping(value = "/batchUnBindUser",method = RequestMethod.GET)
    public ObjectResponse batchUnBindUser(@RequestParam(value = "deviceId",defaultValue = "") Long deviceId,@RequestParam(value = "userIds",defaultValue = "") List<Long> userIds){
        //批量解除绑定
        if (CollectionUtils.isEmpty(userIds)){
            return ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),"无效数据");
        }
        userIds.forEach(userId -> {
            //查询当前是否绑定
            UDev uDev = iuDevService.selectByUserIdAndDevId(deviceId, userId);
            if (Objects.nonNull(uDev)){
                //删除绑定信息
                Map<String,Object> params = Maps.newHashMap();
                params.put("user_id",userId);
                params.put("dev_id",deviceId);
                uDevDao.deleteByMap(params);
            }
        });
        return ResultTools.success(null);
    }
}
